package com.hz.ruoyiequipment.warning.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hz.ruoyiequipment.warning.domain.vo.*;
import com.hz.ruoyiequipment.warning.mapper.AgrAlertLinkMapper;
import com.hz.ruoyiequipment.warning.service.AgrAlertLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AgrAlertLinkServiceImpl
 * @Description
 * @Author 陈萝瑶
 * @Date 2025/3/10 12:07
 */
@Service
public class AgrAlertLinkServiceImpl implements AgrAlertLinkService {
    @Autowired
    private ThresholdRedisService thresholdRedisService;

    @Autowired
    private AgrAlertLinkMapper agrAlertLinkMapper;

    @Override
    public List<AgrAlertLinkVo> getByBatchName(Long batchId) {
        return agrAlertLinkMapper.getByBatchName(batchId);
    }

    @Override
    public List<AgrAlertLinkVo> getSourceEquipment(Long breedId, Long batchId) {
        return agrAlertLinkMapper.getSourceEquipment(breedId,batchId);
    }
    @Override
    public List<AgrAlertLinkVo> getTargetEquipment(Long breedId, Long batchId) {
        return agrAlertLinkMapper.getTargetEquipment(breedId,batchId);
    }

    @Override
    public List<AgrAlertLinkResultVo> getAllByBreedId(Long breedId) {
        return agrAlertLinkMapper.getAllByBreedId(breedId);
    }

    @Override
    public List<AgrAlertLinkVo> getBatchByPlotsId(Long plotsId, Integer batchStatus) {
        return agrAlertLinkMapper.getBatchByPlotsId(plotsId,batchStatus);
    }
    @Override
    public List<AgrAlertLinkVo> getByBreedId(Long breedId,Long plotsId) {
        return agrAlertLinkMapper.getByBreedId(breedId,plotsId);
    }

    @Override
    public List<AgrAlertLinkResultVo> getTriggerByBreedId(Long breedId){
        return agrAlertLinkMapper.getTriggerByBreedId(breedId);
    }

    @Override
    public int delTrigger(Long fieldId) {
        agrAlertLinkMapper.delLink(fieldId);
        return agrAlertLinkMapper.delTrigger(fieldId);
    }

    @Override
    public int insertAgrAlertThresholdField(AgrAlertLinkResultVo agrAlertLinkResultVo) {
        String triggersString = agrAlertLinkResultVo.getTriggers();
        Long breedId = null;
        List<Trigger> triggers = new ArrayList<>();
        Trigger tri = null;
        ObjectMapper objectMapper = new ObjectMapper();
        // 去掉首尾的方括号
        triggersString = triggersString.replaceAll("^\\[|\\]$", "");
        String[] triggerArray = splitJsonArray(triggersString);
        for (String trigger : triggerArray){
            try {
                tri = objectMapper.readValue(trigger, Trigger.class);
                triggers.add(tri);
                System.out.println(tri);
                AgrAlertLinkVo  alertLinkVo1 = agrAlertLinkMapper.getEquip(tri.getDevice());
                Long equipmentId = alertLinkVo1.getEquipmentId();
                tri.setDevice(equipmentId.toString());
                String batchName = tri.getBatch();
                AgrAlertLinkVo alertLinkVo = agrAlertLinkMapper.getBreedId(batchName);
                breedId = alertLinkVo.getBreedId();
                tri.setBreedId(breedId);
                tri.setThresholdId(breedId);
                AgrAlertLinkResultVo field = agrAlertLinkMapper.getFieldId(tri.getThresholdId(),tri.getCondition());
                if (field == null){
                    //新增阈值字段
                    agrAlertLinkMapper.insertAgrAlertThresholdField(tri);
                    AgrAlertLinkResultVo field1 = agrAlertLinkMapper.getFieldId(tri.getThresholdId(),tri.getCondition());
                    Long fieldId = field1.getFieldId();
                    tri.setFieldId(fieldId);
                    agrAlertLinkMapper.insertTriggerAgrAlertLink(tri);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return 0;
            }
        }
        return 1;
    }

    @Override
    public int insertFieldLink(AgrAlertLinkResultVo agrAlertLinkResultVo) {
        int i = insertAgrAlertThresholdField(agrAlertLinkResultVo);
        if (i>0){
            updateAgrAlertEquipLink(agrAlertLinkResultVo);
        }
        return 1;
    }

    @Override
    public int updateAgrAlertEquipLink(AgrAlertLinkResultVo agrAlertLinkResultVo) {
        String triggersString = agrAlertLinkResultVo.getTriggers();
        Long breedId = null;
        List<Trigger> triggers = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        String actionsString = agrAlertLinkResultVo.getActions();
        List<Action> actions = new ArrayList<>();
        // 去掉首尾的方括号
        actionsString = actionsString.replaceAll("^\\[|\\]$", "");
        String[] actionArray = splitJsonArray(actionsString);
        // 去掉首尾的方括号
        triggersString = triggersString.replaceAll("^\\[|\\]$", "");
        String[] triggerArray = splitJsonArray(triggersString);
        Trigger tri = null;
        List fieldIds = new ArrayList<>();
        for (String trigger : triggerArray) {
            tri = null;
            try {
                tri = objectMapper.readValue(trigger, Trigger.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            triggers.add(tri);
            AgrAlertLinkVo  alertLinkVo1 = agrAlertLinkMapper.getEquip(tri.getDevice());
            Long equipmentId = alertLinkVo1.getEquipmentId();
            tri.setDevice(equipmentId.toString());
            String batchName = tri.getBatch();
            AgrAlertLinkVo alertLinkVo = agrAlertLinkMapper.getBreedId(batchName);
            breedId = alertLinkVo.getBreedId();
            tri.setBreedId(breedId);
            tri.setThresholdId(breedId);
            AgrAlertLinkResultVo field = agrAlertLinkMapper.getFieldId(tri.getThresholdId(), tri.getCondition());
            Long fieldId = field.getFieldId();
            fieldIds.add(fieldId);
        }
        for (String action : actionArray){
            try {
                Action act = objectMapper.readValue(action, Action.class);
                actions.add(act);
                AgrAlertLinkVo  alertLinkVo1 = agrAlertLinkMapper.getEquip(act.getDevice());
                Long equipmentId = alertLinkVo1.getEquipmentId();
                act.setDevice(equipmentId.toString());
                AgrAlertLinkVo  alertLinkVo2 = agrAlertLinkMapper.getEquip(act.getTargetDevice());
                Long equipmentId1 = alertLinkVo2.getEquipmentId();
                act.setTargetDevice(equipmentId1.toString());
                //获取condition
                AgrAlertLinkResultVo agr = agrAlertLinkMapper.getConId(act.getCondition());
                act.setCondition(String.valueOf(agr.getExceptionId()));
                act.setThresholdId(tri.getThresholdId());
                fieldIds.forEach(fieldId -> {
                List<Trigger> trigger = agrAlertLinkMapper.selectAgrAlertEquip(Long.valueOf(act.getDevice()),(Long) fieldId);
                if (trigger.size() == 0) {
                    //修改触发器
                    AgrAlertLinkResultVo agrAlertLinkResultVo2 = agrAlertLinkMapper.selectActFieldId(act);
                    if (agrAlertLinkResultVo2 == null){
                        act.setFieldId((Long) fieldId);
                        agrAlertLinkMapper.insertAgrAlertLink(act);
                    }else {
                        act.setFieldId(agrAlertLinkResultVo2.getFieldId());
                        trigger.forEach(trigger1 -> {
                            if (!trigger1.getCondition().equals(agrAlertLinkResultVo2.getExeCondition())){
                                act.setCondition(trigger1.getCondition());
                                agrAlertLinkMapper.updateAgrAlertEquipLink(act);
                            }
                        });
                    }
                    //存在
                } else if (trigger.size() != 0) {
                    //对比fieldId
                    AgrAlertLinkResultVo agrAlertLinkResultVo1 = agrAlertLinkMapper.selectActFieldId(act);
                    if (agrAlertLinkResultVo1 == null){
                        //修改触发器
                        act.setFieldId((Long) fieldId);
                        agrAlertLinkMapper.updateAgrAlertEquipLink(act);
                    }
                }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 1;
    }

    @Override
    public int updateAgrAlertField(Long breedId, Long batchId) {
        return agrAlertLinkMapper.updateAgrAlertField(breedId,batchId);
    }

    @Override
    public List<AgrAlertLinkResultVo> getAllBySourceId(Long sourceId) {
        // 先从 Redis 中获取数据
        Map<String, AgrAlertLinkResultVo> rules = thresholdRedisService.getThresholdRules(sourceId);
        List<AgrAlertLinkResultVo> dbRules= new ArrayList<>(rules.values());
        // 如果 Redis 中没有数据，则从数据库中查询
        if (rules == null || rules.isEmpty()) {
           dbRules = agrAlertLinkMapper.getAllBySourceId(sourceId);
            // 将数据库查询结果写入 Redis
            if (dbRules != null && !dbRules.isEmpty()) {
                for (AgrAlertLinkResultVo rule : dbRules) {
                    String ruleId = "rule:" + rule.getFieldId();
                    thresholdRedisService.updateThresholdRules(sourceId, ruleId, rule);
                }
            }


        }

        // 如果 Redis 中有数据，将 Map 转换为 List
        return dbRules;

    }


    private String[] splitJsonArray(String jsonArray) {
        List<String> result = new ArrayList<>();
        int start = 0;
        int depth = 0;
        for (int i = 0; i < jsonArray.length(); i++) {
            char c = jsonArray.charAt(i);
            if (c == '{') {
                if (depth == 0) {
                    start = i;
                }
                depth++;
            } else if (c == '}') {
                depth--;
                if (depth == 0) {
                    result.add(jsonArray.substring(start, i + 1));
                }
            }
        }
        return result.toArray(new String[0]);
    }

}
